package com.augurit.wf.app.document.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;

import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.base.action.ExtBaseAction;
import com.augurit.common.sysfile.service.ISysFileService;
import com.augurit.common.sysfile.web.form.SysFileForm;
import com.augurit.common.system.util.WebContextUtils;
import com.augurit.common.util.ExtUtils;
import com.augurit.common.util.FileUtils;
import com.augurit.wf.app.document.entity.DocConfig;
import com.augurit.wf.app.document.service.IDocConfigService;
import com.augurit.wf.app.document.service.IdocCategory;
import com.augurit.wf.app.document.utils.DateUtil;
import com.augurit.wf.app.document.utils.FileUtil;
import com.augurit.wf.app.document.web.form.DocAddForm;
import com.augurit.wf.app.document.web.form.DocCategoryForm;
import com.augurit.wf.app.document.web.form.DocumentForm;





@SuppressWarnings("serial")
@Results({
	@Result(name = CrudActionSupport.RELOAD, location = "document-manager.action", type = "redirect"),
	@Result(name = CrudActionSupport.SUCCESS, location = "/wf/app/document/document-manager.jsp"),
	@Result(name ="DOWN", location = "download.action?id=${id}", type = "redirect"),
	@Result(name ="NOTEXIT", location = "/wf/app/document/filenotexit.jsp")
	
})
public class DocumentManagerAction extends ExtBaseAction {
	
	@Autowired
	private IdocCategory docCategoryImpl;
	
	@Autowired
	private IDocConfigService docConfigService;
	
	@Autowired
	private ISysFileService sysFileService;
	
	private DocAddForm form;
	
	private Long[] docIds;
	
	private Long dirId;
	
	private String id;
	
	private Long[] sysFileIds;
	
	private Long parentCid;
	
	private String docName;
	
	private Page<DocumentForm> page = new Page<DocumentForm>();
	
    public String archive() throws Exception {
    	if(docName != null && !docName.equals("") && parentCid != null && parentCid >= 0){
    		List<DocCategoryForm> list = docCategoryImpl.getCategoryUnderGivenCategory(parentCid, docName);
    		if(null != list && list.size() > 0){
    			ExtBaseAction.extRenderFailture("该文所属附件已归档到您所指定的目录中！");
    			return null;
    		}
    	}else{
    		ExtBaseAction.extRenderFailture("归档失败！");
    		return null;
    	}
    	if(sysFileIds != null && sysFileIds.length > 0){
    		
    		//以文件名为名称创建一个目录
			DocCategoryForm dcf = new DocCategoryForm();
			dcf.setName(docName);
			dcf.setPid(parentCid);
			dcf.setVersion(getSysVersion());
			docCategoryImpl.catSave(dcf);
    		
    		for(Long fileId:sysFileIds){
    			//获取附件对象
    			SysFileForm sff = sysFileService.get(fileId);
    			if(null != sff){    				
    				//将文件归档到创建的目录中
    				//复制文件到文档目录下
    				String newFileName = FileUtils.copy(getRequest().getRealPath(
							sff.getFilePath() + "/" + sff.getFileName()),
							getPath(dcf.getVersion()) + sff.getFileName(), true);
    				
    				//将数据写入数据库
    				DocumentForm df = new DocumentForm();
    				df.setCid(dcf.getId());
    				df.setDocType("."+sff.getFileFormat());
    				df.setFileName(sff.getFileName());
    				df.setName(sff.getFileName());
    				df.setPovd(DateUtil.parseDate("3011-12-30", "yyyy-MM-dd"));
    				String context = getRequest().getContextPath().substring(1);
    				df.setUrl(newFileName.substring(newFileName.indexOf(context)));
    				df.setVersion(dcf.getVersion());
    				docCategoryImpl.saveDoc(df);
    			}
    		}
    		ExtBaseAction.extRenderSuccess("归档成功！");
    	}else{
    		ExtBaseAction.extRenderFailture("归档失败！");
    	}
    	return null;
    }

    public static void main(String[] args){
    	String s = "D:/tomcat-6.0.29/webapps/engine5/User/document/2011/duban.jpdl（1）.xml";
    	System.out.println(s.substring(s.indexOf("engine5")));
    }
    
	public String excute()  throws Exception {
		//System.out.println("NoticeManagerAction is coming");
		return "SUCCESS";
	}
	
	public String doclist() throws Exception{
		
		ExtUtils.initPageFromExtGridParam(this.getRequest(), page);
		docCategoryImpl.searchDocuments(page, getFormforSearch());
		this.extRenderGridJson(page);
		return null;
		
	}
	
	public String predownload()throws Exception{
		String url=null;
		if(id!=null&&id.length()>0){
			//id 为"-1"，表示是帮助文档
           if("-1".equals(id)){
				url=WebContextUtils.HELP_DOC_PATH;
			}else{
				url=docCategoryImpl.findDocUrl(Long.valueOf(id));
			}
		}

		File newFile =null;
		if(url!=null && url.length()>0)
		{   
			String myurl=this.getSysRealPath()+url.substring(7);
		    newFile =new File(myurl);
		}
		System.out.println("url:"+newFile.getPath());
		if(newFile!=null &&newFile.exists()){
			return "DOWN";
		}else{
			return "NOTEXIT";
		}
	}
	
	
	public DocumentForm getFormforSearch(){
		DocumentForm form =new DocumentForm();
		form.setCid(this.dirId);
		System.out.println("dirId:"+this.dirId);
		form.setName(this.getRequest().getParameter("name"));
		form.setFileName(this.getRequest().getParameter("fileName"));
		form.setDocType(this.getRequest().getParameter("docType"));
		form.setStatus(this.getRequest().getParameter("status"));
		return form;
		
	}
	
	
	public String docload() throws Exception{
		try {
			Long id=Long.valueOf(this.getRequest().getParameter("id"));
			if(id!=null){
				DocumentForm form=docCategoryImpl.findDoc(id);
				DocAddForm form2 =new DocAddForm();
				form2.setDirName(docCategoryImpl.findCatName(form.getCid()));
				form2.setName(form.getName());
				form2.setId(form.getId());
				SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
				form2.setPovd(format.format(form.getPovd()));
				form2.setStatus(form.getStatus());
				form2.setVersion(form.getVersion());
				this.renderJson(this.getJsonString(form2));
			}else{
				this.extRenderFailture();
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		
		
		return null;
	}

	public String docsave() throws Exception{
	   Long cid=null;
	   if(this.form.getDirName()!=null){
				cid=docCategoryImpl.findByName(this.form.getDirName());//文档所在的目录ID
			}
	   Long id =this.form.getId();
	   if(id!=null){
		   try {
			//修改文档
			   DocumentForm form2=docCategoryImpl.findDoc(id);
			   form2.setName(this.form.getName());
			   form2.setCid(cid);
			   String povd =this.form.getPovd();//文档的有效日期
				SimpleDateFormat format =new SimpleDateFormat("yy年MM月dd日");
				java.util.Date date=null;
				if(povd!=null){
					date =format.parse(povd);
				}
			   form2.setPovd(date);
			   form2.setStatus(this.form.getStatus());
			   form2.setVersion(this.form.getVersion());
			   docCategoryImpl.saveDoc(form2);
			   String msg = "{success:true}";   
			   this.getResponse().getWriter().print(msg);
		} catch (RuntimeException e) {
			 String msg = "{success:false}";   
			this.getResponse().getWriter().print(msg);
			System.out.println(e);
		}   
	   }else{
		try {
			//先将除了doctype,filename,url的以外的信息保存
			String name =this.form.getName();//上传的文件名称
			String povd =this.form.getPovd();//文档的有效日期
			SimpleDateFormat format =new SimpleDateFormat("yy年MM月dd日");
			java.util.Date date=null;
			if(povd!=null){
				date =format.parse(povd);
			}
			String version =this.form.getVersion();
			if(version !=null &&version.length()>0){
			}else{
				version=this.getSysVersion();
			}
			String status =this.form.getStatus();
			DocumentForm form1=new DocumentForm();
			form1.setCid(cid);
			form1.setPovd(date);
			form1.setVersion(version);
			form1.setName(name);
			form1.setStatus(status);
			docCategoryImpl.saveDoc(form1);
			Long formId =form1.getId();
			String path =getPath();
			String docType=null;
			if(path != null){
				docType =this.form.getLoadFileName().substring(this.form.getLoadFileName().lastIndexOf("."));
			}
			form1.setDocType(docType);
			String fileName=this.form.getLoadFileName();
			if(this.form.getFileName()!=null && this.form.getFileName().length()>0){
				fileName=this.form.getFileName().trim()+docType;
			}
			form1.setFileName(fileName);
			String url=path+fileName;
			//包含id的文件
			String fullFileName=url.substring(0, url.lastIndexOf("."))+form1.getId()+docType;
			String realUrl=fullFileName.substring(fullFileName.lastIndexOf("\\")+1);
			form1.setUrl(realUrl);
			//将其余的信息也保存
			docCategoryImpl.saveDoc(form1);
			
			//保存上传的文件
			File pathFile = new File(path);
			if(!pathFile.exists()){
				pathFile.mkdirs();
			}
			
			File oldFile = new File(fullFileName);
			File reFile = new File(fullFileName+".1");
			
			if(oldFile.exists()){
				oldFile.renameTo(reFile);
				reFile.delete();
			}
			
			File newFile =new File(fullFileName);
			FileUtil.copy(this.form.getLoad(),newFile );
			
			 String msg = "{success:true}";   
		       this.getResponse().getWriter().print(msg);  

			
		} catch (Exception e) {
			System.out.println(e);
			String msg = "{success:false}";   
            this.getResponse().getWriter().print(msg);   
		}
		}
		return NONE; 
	}

	
	
	
	
	public DocAddForm getForm() {
		return form;
	}

	public void setForm(DocAddForm form) {
		this.form = form;
	}
	
	
	private String getPath(){
		DocConfig config =docConfigService.findConfigByName("DOC_PATH");
		String path = null;
		String version =this.form.getVersion();
		if(version== null){
			version=this.getSysVersion();
		}
		
		if(config.getType() != null && config.getType().equals("LOCAL")){
			path = this.getSysRealPath()+"/"+config.getConfig()+"/"+this.form.getVersion()+"/";
		}else{
			path = config.getConfig()+"/"+this.form.getVersion()+"/";
		}
		//返回路径
		return path;
		
	}
	
	private String getPath(String version){
		DocConfig config =docConfigService.findConfigByName("DOC_PATH");
		String path = null;
		if(version== null){
			version=this.getSysVersion();
		}		
		if(config.getType() != null && config.getType().equals("LOCAL")){
			path = this.getSysRealPath()+"/"+config.getConfig()+"/"+version+"/";
		}else{
			path = config.getConfig()+"/"+version+"/";
		}
		//返回路径
		return path;
		
	}
	
	
	public String docdelete() throws Exception{
	
       try {
		Boolean flag=docCategoryImpl.deletedocs(this.getSysRealPath(),docIds);
		if(flag){
			this.extRenderSuccess();
		}else{
			System.out.println("删除文件出错");
			this.extRenderFailture();
		}
		
	} catch (RuntimeException e) {
		this.extRenderFailture();
		e.printStackTrace();
	}
		
		return null;
	}
	
	
	
	
	
	
	

	public Long[] getDocIds() {
		return docIds;
	}

	public void setDocIds(Long[] docIds) {
		this.docIds = docIds;
	}

	public Long getDirId() {
		return dirId;
	}

	public void setDirId(Long dirId) {
		this.dirId = dirId;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Long[] getSysFileIds() {
		return sysFileIds;
	}

	public void setSysFileIds(Long[] sysFileIds) {
		this.sysFileIds = sysFileIds;
	}

	public Long getParentCid() {
		return parentCid;
	}

	public void setParentCid(Long parentCid) {
		this.parentCid = parentCid;
	}

	public String getDocName() {
		return docName;
	}

	public void setDocName(String docName) {
		this.docName = docName;
	}

}
